// 20.有效的括号
package LeetcodeHot100;

import java.util.Deque;
import java.util.LinkedList;

public class Solution020 {
    public boolean isValid(String s) {
        if (s == null)
            return true;
        if (s.length() % 2 == 1)
            return false;
        Deque<Character> stack = new LinkedList<>();
        stack.push(s.charAt(0));
        for (int i = 1; i < s.length(); i++) {
            if (s.charAt(i) == ')') {
                if (stack.isEmpty() || stack.poll() != '(')
                    return false;
            } else if (s.charAt(i) == ']') {
                if (stack.isEmpty() || stack.poll() != '[')
                    return false;
            } else if (s.charAt(i) == '}') {
                if (stack.isEmpty() || stack.poll() != '{')
                    return false;
            } else {
                stack.push(s.charAt(i));
            }
        }
        return stack.isEmpty();
    }
}
